from __future__ import absolute_import

from . import token
from scopt.util import message as msg_util
from scopt.util.message_types import STRING


@token(version='0.1',
       token={'type': 'security.flyby.token',
              'value': STRING(required=True)})
def handle(data_packet, registry):
    # TODO: Invalidate token after time period
    security_token = msg_util.get_security_token(data_packet)
    token_string = security_token['value']
    result = registry.query('users',
                            where=[['users.token', token_string]])
    if len(result) == 0:
        return msg_util.exception(data_packet, 'security.invalid.token')
    user = result[0]
    login = 'ADMIN' if user['admin'] else user['login']
    data_packet['security'] = {'principal': {'login': login,
                                             'username': user['username']}}
    return data_packet
